#!/usr/bin/perl

#input1 time1, usually receive_time of pure wire case
#input2 time2, usually receive_time from external network
#output2 delay of each packet in sequence
#output2 stats (mean, variance, std, jitter)
#input1 and input2 should have same amount of data points
#output3 to store results of multiple runs into same file, used for plotting

open(INPUT1, $ARGV[0]) or die "$ARGV[0] cannot be opened.\n";
open(INPUT2, $ARGV[1]) or die "$ARGV[1] cannot be opened.\n";
open(OUTPUT1, ">$ARGV[2]") or die "$ARGV[2] cannot be created.\n";
open(OUTPUT2, ">$ARGV[3]") or die "$ARGV[3] cannot be created.\n";
open(OUTPUT3, ">>$ARGV[4]") or die "$ARGV[4] cannot be created.\n";

$counter = 0;
$sum = 0;
$square_sum = 0;
$mean = 0;
$var = 0;
$std = 0;
$jitter_total = 0;
$jitter = 0;

#remove first 5 lines due to ipsumdump
#for($i=1; $i<=5; $i++)
#{
#	$line1 = <INPUT1>;
#	$line2 = <INPUT2>;
#}

#get first data, from jitter calculation
$line1 = <INPUT1>;
chomp($line1);
$line2 = <INPUT2>;
chomp($line2);
$delay=$line2-$line1;
$formatted_delay=sprintf("%.9f", $delay);
print OUTPUT1 "$formatted_delay\n";
$counter++;
$sum += $delay;
$square_sum += $delay**2;
$pre_delay = $delay;

while($line1 = <INPUT1>)
{			
	chomp($line1);

	$line2 = <INPUT2>;
	chomp($line2);

#INPUT2-INPUT1
	$delay=$line2-$line1;
	$formatted_delay=sprintf("%.9f", $delay);
	print OUTPUT1 "$formatted_delay\n";

	$counter++;
	$sum += $delay;
#print "sum = $sum\n";
	$square_sum += $delay**2;
	$jitter_total += abs($delay-$pre_delay);
        $pre_delay = $delay;
}
#print "counter = $counter\n";
#print "sum = $sum\n";
#print "square_sum = $square_sum\n";

$mean = $sum /$counter;
$autocor = $square_sum/$counter;
$var = $autocor-$mean**2;
$std = sqrt($var);
$jitter = $jitter_total/($counter-1);

$mean=$mean*(10**6);
$var=$var*(10**6);
$std=$std*(10**6);
$jitter=$jitter*(10**6);

$formatted_mean=sprintf("%.3f", $mean);
$formatted_var=sprintf("%.3f", $var);
$formatted_std=sprintf("%.3f", $std);
$formatted_jitter=sprintf("%.3f", $jitter);

print OUTPUT2 "mean = $formatted_mean\n";
print OUTPUT2 "var = $formatted_var\n";
print OUTPUT2 "std = $formatted_std\n";
print OUTPUT2 "jitter = $formatted_jitter\n";

print OUTPUT3 "$formatted_mean $formatted_std $formatted_jitter\n";

close(INPUT1);
close(INPUT2);
close(OUTPUT1);
close(OUTPUT2);
